<template>
  <div class="audit">
    <div class="card-container mb-2">
      <div class="audit-title">
        配置推送审核
        <Tag
          class="ml-2"
          :color="auditInfo.auditStatus == '1' ? 'green' : 'orange'"
          >{{ auditStatusEnum[auditInfo.auditStatus as keyof typeof auditStatusEnum] }}</Tag
        >
      </div>
      <Row class="mb-2.5">
        <Col :span="6">
          <span class="audit-txt">创建时间</span>
          <span>{{ auditInfo.createTime }}</span>
        </Col>
        <Col :span="4">
          <span class="audit-txt">申请人</span>
          <span>{{ auditInfo.createBy }}</span>
        </Col>
        <Col :span="6">
          <span class="audit-txt">审核时间</span>
          <span>{{ auditInfo.auditTime ? auditInfo.auditTime : '--' }}</span>
        </Col>
        <Col :span="4">
          <span class="audit-txt">审核人</span>
          <span>{{ auditInfo.auditBy ? auditInfo.auditBy : '--' }}</span>
        </Col>
      </Row>
    </div>

    <Row :gutter="10">
      <Col :span="4">
        <div :class="['card-container', 'scroll-container']">
          <p>推送方式</p>
          <span>{{ auditInfo.pushType == '2' ? '设备推送' : '项目推送' }}</span>
          <p class="mt-2">配置编码ID</p>
          <span>{{ auditInfo.code }}</span>
          <p class="mt-2">推送说明</p>
          <span>{{ auditInfo.pushDesc }}</span>
          <p class="mt-2">协议版本号</p>
          <span>{{ auditInfo.protobufVersion }}</span>

          <div class="info-item">
            <p class="mt-2">设备类型/型号</p>
            <Tree
              :tree-data="auditInfo.modelAlwaysVOS"
              :field-names="fileNames"
            />
          </div>
          <p class="mt-2">配置说明</p>
          <span>{{ auditInfo.configExplain }}</span>
          <div class="info-item">
            <p class="mt-2">配置类别</p>
            <Tree
              :tree-data="JSON.parse(auditInfo.configType)"
              v-if="
                auditInfo.configType && auditInfo.configType.startsWith('[{')
              "
            />
            <Popover
              placement="right"
              trigger="hover"
              :overlayStyle="{ width: '100px' }"
              overlayClassName="popovper-dark"
              v-else-if="
                auditInfo.configType &&
                auditInfo.configType.split(',').length > 2
              "
            >
              <template #content>
                <ul>
                  <li v-for="item in auditInfo.configType.split(',')">
                    {{ item }}
                  </li>
                </ul>
              </template>
              <div class="truncate w-full" v-html="auditInfo.configType"></div>
            </Popover>
            <div
              v-else
              class="truncate w-full"
              v-html="auditInfo.configType"
            ></div>
          </div>
        </div>
      </Col>
      <Col :span="20">
        <div class="card-container" v-if="auditInfo.pushType == '2'">
          <Row>
            <Col :span="6">
              <p>项目总数</p>
              <span>{{ statistics.projectNum }}</span></Col
            >
            <Col :span="3">
              <p>已选设备总数</p>
              <span>{{ dataSource.length }}</span></Col
            >
            <Col :span="3" v-for="(item, index) in statistics.typeList">
              <p>{{ item.typeName }}</p>
              <span>{{ item.sum }}</span>
            </Col>
          </Row>
        </div>
        <Row justify="start">
          <Col>
            <div class="table-title">推送列表</div>
          </Col>
        </Row>
        <Table
          :showExpandColumn="false"
          class="device_table"
          :columns="auditInfo.pushType == '2' ? columnsDevice : columnsProject"
          size="middle"
          :scroll="{ x: 500, y: scrollHeight }"
          :class="{ device: pushType == '2' }"
          :data-source="dataSource"
        >
        </Table>
      </Col>
    </Row>
  </div>
</template>
<script setup lang="tsx">
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import {
  Col,
  Modal,
  Popover,
  Row,
  Table,
  type TableProps,
  Tag,
  Tree,
  TreeProps,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { columnWidth, listToEnum } from '@/utils/utils';
import {
  appUpdateTypeEnum,
  appUpdateTypeOption,
  auditStatusEnum,
  packageTypeEnum,
} from '@/constant/push';
import { fetchDictsOfType } from '@/api/dict';
import { approvalQuickConfigTask, getDeviceMode } from '@/api/push';

const scrollHeight = ref(0);
onMounted(() => {
  const dom = document.querySelector('.device_table');
  scrollHeight.value = dom?.getBoundingClientRect().height - 40 || 0;
});
const props = defineProps({
  audit: {
    type: Object,
    default: {},
  },
  pushType: {
    type: String,
    default: '',
  },
});
watch(
  () => props.audit,
  (newVal) => {
    if (newVal.pushType == '2') {
      dataSource.value = newVal.deviceList;
    } else {
      dataSource.value = newVal.projectList;
    }
    statistics.value = newVal.statistics;
    auditInfo.value = newVal;
  },
  { deep: true },
);
const statistics = ref({
  projectNum: 0,
  deviceNum: 0,
  typeList: [
    {
      typeName: '预警终端',
      sum: 0,
    },
    {
      typeName: '预警喇叭',
      sum: 0,
    },
    {
      typeName: '桌面终端',
      sum: 0,
    },
  ],
});
const auditInfo = ref<any>({});
const dataSource = ref([]);
const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};
const modalList = ref<any[]>([]);
const sysDeviceModeEnum = ref<Record<string, any>>({});
onMounted(() => {
  fetchDictsOfType(['sys_device_mode']).then((res: any) => {
    const { sys_device_mode } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
  });
  getDeviceMode({}).then((res) => {
    modalList.value = res.data as any;
  });
});
const formatModal = (val: any) => {
  let arr = modalList.value.filter((item) => {
    return item.modelId == val;
  });
  return arr[0]?.model;
};
const columnsDevice = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'shortName',
    align: 'center',
    width: columnWidth('shortName', dataSource.value, '所属项目'),
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    width: columnWidth('deviceCode', dataSource.value, '设备序列号'),
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    align: 'center',
    // customRender({ text, record }) {
    //   return text + (record.versionCode ? `(${record.versionCode})` : '');
    // },
    width: columnWidth('softwareVersion', dataSource.value, '所属项目', 20),
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
    align: 'center',
    width: columnWidth('firmwareVersion', dataSource.value, '所属项目'),
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    align: 'center',
    customRender({ text }) {
      return formatModal(text);
    },
    width: columnWidth('modelId', dataSource.value, '所属项目', 20),
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    width: columnWidth('deviceType', dataSource.value, '所属项目'),
    customRender({ text }) {
      return sysDeviceModeEnum.value[text as string];
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    align: 'center',
    width: columnWidth('address', dataSource.value, '所属项目'),
  },
]);
const columnsProject = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'projectName',
    align: 'center',
    width: columnWidth('projectName', dataSource.value, '所属项目'),
  },
  // {
  //   title: '设备类型/型号',
  //   dataIndex: 'modelAlwaysVOS',
  //   align: 'center',
  //   width: 240,
  //   customRender: ({ record }) => {
  //     const fileNames: TreeProps['fieldNames'] = {
  //       title: 'typeName',
  //       children: 'modeName',
  //     };
  //     return h(Tree, {
  //       treeData: record.modelAlwaysVOS,
  //       fieldNames: fileNames,
  //     });
  //   },
  // },
  {
    title: '可选设备总数',
    dataIndex: 'count',
    align: 'center',
    width: columnWidth('count', dataSource.value, '所属项目'),
  },
  {
    title: '项目说明',
    dataIndex: 'projectRemark',
    align: 'center',
    width: columnWidth('projectRemark', dataSource.value, '所属项目'),
  },
]);
const emit = defineEmits(['versionAudit']);

const onConfirm = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      const _params = new FormData();
      _params.append('id', auditInfo.value.id);
      _params.append('approvalStatus', '1');

      await approvalQuickConfigTask(_params);
      message.success('审核成功');
      emit('versionAudit', true);
    },
  });
};
defineExpose({
  onConfirm,
});
</script>
<style lang="scss" scoped>
.audit-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  color: var(--text-color);
}

.audit-txt {
  margin-right: 12px;
  color: #fff;
}
.table-title {
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
.audit-code {
  margin: 10px 0;
  font-weight: bold;
}
.scroll-container {
  height: calc(63vh - 115px);
  overflow-y: auto;
  p {
    position: relative;
    color: #fff;
    &::before {
      position: absolute;
      left: -8px;
      top: 50%;
      transform: translateY(-50%);
      content: '';
      width: 2px;
      height: 12px;
      background-color: #1890ff;
    }
  }
}
:deep(.ant-table) {
  height: calc(60vh - 176px);
}
:deep(.ant-table-body) {
  height: calc(60vh - 216px);
}
.device {
  :deep(.ant-table) {
    height: calc(60vh - 260px);
  }
  :deep(.ant-table-body) {
    height: calc(60vh - 300px);
  }
}
</style>
